package com.demo.zhlg.config;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.demo.zhlg.util.Result;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    public ResponseEntity<Result> genResult(Result result ){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE );
        return new ResponseEntity<>( result, headers, HttpStatus.OK );
    }

    @ExceptionHandler(value = SignatureVerificationException.class)
    @ResponseBody
    public ResponseEntity<Result> jwtFailed(Exception e){
        return genResult(Result.error(Result.AUTHENTICATION_FAILED));
    }

    @ExceptionHandler(value = Exception.class )
    @ResponseBody
    public ResponseEntity<Result> general( Exception e){
        return genResult(Result.error(Result.GENERAL_ERROR));
    }

    @ExceptionHandler({JWTDecodeException.class, TokenExpiredException.class})
    @ResponseBody
    public ResponseEntity<Result> checkFailed(Exception e){
        return genResult(Result.checkFailed());
    }

    @ExceptionHandler({BadCredentialsException.class, InternalAuthenticationServiceException.class})
    @ResponseBody
    public ResponseEntity<Result> loginFailed(Exception e){
        return genResult(Result.loginFailed());
    }

    @ExceptionHandler(value = InsufficientAuthenticationException.class)
    @ResponseBody
    public ResponseEntity<Result> authenticationFailed(Exception e){
        return genResult(Result.checkFailed());
    }
}